// <copyright file="RoleRepository.cs" company="EnterpriseApi">
// Copyright (c) EnterpriseApi. All rights reserved.
// </copyright>

using EnterpriseApi.Data;
using EnterpriseApi.Models;
using Microsoft.EntityFrameworkCore;

namespace EnterpriseApi.Repositories;

/// <summary>
/// 角色仓储实现类，提供角色特有的数据访问操作
/// </summary>
public class RoleRepository : Repository<Role>, IRoleRepository
{
    private readonly AppDbContext _context;

    /// <summary>
    /// 初始化RoleRepository的新实例
    /// </summary>
    /// <param name="context">数据库上下文</param>
    public RoleRepository(AppDbContext context) : base(context)
    {
        _context = context;
    }

    /// <summary>
    /// 根据角色名称获取角色
    /// </summary>
    /// <param name="name">角色名称</param>
    /// <returns>角色对象，如果不存在则返回null</returns>
    public async Task<Role?> GetByNameAsync(string name)
    {
        return await _context.Roles.FirstOrDefaultAsync(r => r.Name == name);
    }

    /// <summary>
    /// 检查角色名称是否已存在
    /// </summary>
    /// <param name="name">角色名称</param>
    /// <returns>角色名称是否已存在</returns>
    public async Task<bool> IsNameExistsAsync(string name)
    {
        return await _context.Roles.AnyAsync(r => r.Name == name);
    }
}